package cn.fancy.sdk.pay.weixin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram.Req;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * Created by zhaojh on date 3/14/21
 */
public class MiniProgramController {
    
    private IWXAPI iwxapi;
    
    /**
     * @param app_id 从官方网站申请到的合法appID
     */
    public void init(Context context, final String app_id) {
        iwxapi = WXAPIFactory.createWXAPI(context, app_id, true);
        //最后一个入参是检查证书错误，错误时会提示register app failed for wechat app signature check failed
        
        iwxapi.registerApp(app_id);
        
        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                iwxapi.registerApp(app_id);
            }
        }, new IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP));
    }
    
    public void callMiniProgram(Context context, final String app_id, String user_name, String path, int mini_program_type) {
        //WXTextObject wxTextObject=new WXTextObject();
        //iwxapi.sendReq()
        if (iwxapi == null) {
            iwxapi = WXAPIFactory.createWXAPI(context, app_id, true);
        }
        WXLaunchMiniProgram.Req req = new Req();
        req.userName = user_name;
        req.path = path;
        req.miniprogramType = mini_program_type;
        //req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_TEST;
        iwxapi.sendReq(req);
    }
    
    //todo 待确认：是否需要新建.wxapi.WXEntryActivity，在onResp()获取返回值
}
